package cn.chenxiejia;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/***
 * @program: maven
 * @ClassName: File12
 * @Description: 统计jdk17单词使用频率
 * @Author: chenxiejia
 * @Date: 2022/1/19 21:56
 * @version : V1.0
 */
public class File12 {
    public static Map<String, Integer> map = new HashMap<>();

    public static void main(String[] args) {
        File file = new File("F:/jdk17_src.txt");
        try (BufferedReader br = new BufferedReader(new FileReader(file))) {
            StringBuilder sb = new StringBuilder();
            Pattern pattern = Pattern.compile("\s[a-zA-Z]{2,}\s");

            while (br.ready()) {
                String s = br.readLine();
                //System.out.println(s);
                Matcher m = pattern.matcher(s);
                //注意循环m.find()
                while (m.find()) {
                    String key = m.group();
                    //System.out.println(key);
                    if (map.containsKey(key)) {
                        map.put(key, map.get(key) + 1);
                    } else {
                        map.put(key, 1);
                    }
                }


//                if (!"".equals(key))
//                    if (map.containsKey(key)) {
//                        map.put(key, map.get(key) + 1);
//                    } else {
//                        map.put(key, 1);
//                    }
//                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
//        Collection<Integer> c = map.values();
//        List<Integer> list = new ArrayList<>(c);
//        Collections.sort(list);
//        System.out.println(list);

        //map.entrySet()将key与value整合为一体，指定Map.Entry类型
        List<Map.Entry<String, Integer>> list = new ArrayList<>(map.entrySet());
        //重写排序方法
        Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
            @Override
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                return o1.getValue().compareTo(o2.getValue());
            }
        });
        System.out.print(list);

        //TreeSet<Map.Entry<String, Integer>> set = (TreeSet<Map.Entry<String, Integer>>) map.entrySet();


        //map.forEach((k, v) -> System.out.printf("%s = %s %n", k, v));
    }
}
